/* 批量编辑属性hooks */
import { ref, reactive, onMounted, computed } from 'vue';
import { cloneDeep } from 'lodash';
export const createProps = (op = {}) => {
  return {
    // 表格配置
    pageConfig: {
      type: Object,
      default: () => ({})
    },
    // 页面标识
    queryType: {
      type: String,
      default: ''
    },
    disabled: {
      type: Boolean,
      default: false
    },
    // 规则详情数据源
    alternativeRuleDetail: {
      type: Object,
      default: () => ({})
    },
    // 零部件详情数据
    partDataDetail: {
      type: Object,
      default: () => ({})
    },
    // 相对列表中数据
    relatePartList: {
      type: Array,
      default: () => []
    },
    ...op
  };
};
export const createEmits = (op = []) => {
  return ['change', ...op];
};
import emitter from '../../../main'



export const useSubstitutionPartTable = (props, emit) => {
  const { proxy } = getCurrentInstance();
  // 查询配置
 
  const toolbarOptions = ref({
    keyword: '',
    showPrevNext: false,
    showSetting: false,
    clearable: true
  });
  // 复选框配置
  const checkboxConfig = reactive({
    trigger: 'default',
    highlight: true,
    reserve: true
  });
  // 初始列
  const originGridOptionsColumns = reactive([
    { type: 'checkbox', width: 60, fixed: 'left' },
    { type: 'seq', title: proxy.$t('table.index'), width: 50, fixed: 'left' }
  ]);
  // 动态列
  const tableColumns = ref([]);
  const showMark = reactive({
    'c/i': 'blue icon-common-normal',
    'c/o': 'yellow icon-a-common-someoneelse',
    wrk: 'red icon-a-common-ipickup'
  });
  // 动态列入参
  const modulekeyParam = ref({
    modulekey: ''
  });
  // 页面加载loading
  const pageLoading = ref(false);
  // 单位iba
  const unitList = ref([]);
  // 页面配置
  const substitutionTableConfig = ref({});
  // 是否已经保存过
  const isSaveData = ref(false);
  // 勾选的数据
  const selection = ref([]);
  // 已经保存过的数据Map
  const updateRecordsParam = ref(null);
  const editVxeTable = ref(null);
  const tableSourceData = ref([]);
  // 所有数据
  const allTableData = ref([]);
  const addSaveData = ref([]);
  const deleteSaveData = ref([]);
  const ibaColumnMap = ref({});
  const defaultIbaValueMap = ref({});
  const gridOptions = computed(() => {
    let obj = {
      // 表格配置
      border: false,
      resizable: true,
      keepSource: true,
      showOverflow: true,
      showHeaderOverflow: true,
      columnKey: true,
      // modify by gejq 2025/1/22 列表最小高度
      minHeight: '64',
      rowConfig: { height: 30, isCurrent: true, keyField: 'rowId' },
      editConfig: {
        autoFocus: true,
        trigger: 'click',
        mode: 'cell',
        showUpdateStatus: true,
        icon: 'fa fa-pencil-square-o',
        beforeEditMethod: activeCellMethod
      },
      checkboxConfig: checkboxConfig,
      sortConfig: { trigger: 'cell' },
      editRules: {},
      columns: [...originGridOptionsColumns, ...tableColumns.value],
      scrollY: { gt: 30, enabled: true },
      scrollX: { gt: 40 },
      cellClassName: cellClassName
    };
    return obj;
  });
  // 按钮配置
  const btnOptions = computed(() => {
    return type => {
      let obj = {
        add: {
          type: 'main',
          title: proxy.$t('btn.add'),
          iconClass: 'iconfont icon-tianjia1',
          disabled: props.disabled
        },
        delete: {
          type: 'neutral',
          title: proxy.$t('btn.remove'),
          iconClass: 'iconfont icon-structure-remove',
          disabled: !selection.value.length || props.disabled
        },

        save: {
          type: 'main',
          title: '测试',
          iconClass: 'iconfont icon-tianjia1',
          disabled: props.disabled
        }
      };
      return obj[type];
    };
  });

  // 获取默认列
  const defaultColumns = computed(() => {
    let propList = originGridOptionsColumns.map(item => item.type);
    return tableColumns.value.filter(item => propList.indexOf(item.type) === -1);
  });
  // 获取可编辑列
  const editColumns = computed(() => {

    return tableColumns.value.filter(item => !item.readOnly);
  });
  // 具名插槽
  const editItem = computed(() => {
    return item => {
      return 'edit.' + item.prop;
    };
  });
  // 根据当前行返回list
  const selectionOrRowList = computed(() => {
    return row => {
      let list = editVxeTable.value?.grid.getCheckboxRecords();
      let flag = row ? list.some(item => item.masteredoid == row.masteredoid) : true;
      let updateList = flag ? list : [row];
      return updateList;
    };
  });
  // 显示label
  const getLabelByColumn = computed(() => {
    return (row = {}, prop = '', column = {}) => {
      let label = '';
      // 下拉布尔值
      const rowCheck = value => {
        // 适配布尔值
        return value == 'true' || value == '1' ? proxy.$t('true') : proxy.$t('false');
      };
      if (column.isIbaProperty) {

        column.options == []

        let ibaList = ibaColumnMap.value[column.prop] || [];
        if (!ibaList?.length) return (label = row[prop] || '');
        let ibaObj = ibaList.find(val => val.uniquelyMark == prop);
        if (ibaObj?.ibaEnumObj) {
          return (label = ibaObj && ibaObj?.ibaEnumObj ? ibaObj?.ibaEnumObj[row[prop]] : row[prop] || '');
        } else {
          if (ibaObj?.constraintForm[0]?.type == 'radio') {
            label = Object.prototype.hasOwnProperty.call(row, prop) && row[prop] ? rowCheck(row[prop]) : '';
          } else {
            label = row[prop] || '';
          }
        }
      } else {
        // 枚举
        if (column.editRender?.enumKey) {
          let enumObj = column.editRender.options.list.find(val => val.value == row[prop]);
          if (enumObj) label = enumObj.label;
        } else {
          label = row[prop] || '';
        }
      }
      return label;
    };
  });
  onMounted(() => {
    initData();
    window.wujieBus?.$on('formRenderMounted', handleEvent);
  });
  /**
   * @description 初始化数据
   * @autor gejq
   * @return {*} 未有对象oid
   */

  const initData = async () => {

    try {
      pageLoading.value = true;
      substitutionTableConfig.value = props.pageConfig;
      modulekeyParam.value = substitutionTableConfig.value.modulekeyParam || {};
      await getDefaultColumnByViewName();
      await getTableData();
      await initTableDataList();
      pageLoading.value = false;
    } catch {
      pageLoading.value = false;
    }
  };
  /**
   * @description 获取表格数据
   * @Autor Gejq
   * @param {*} substitutionTableConfig 批量编辑配置
   */
  let specMap = new Map();
  
  let manufactureUomMap = new Map(); // 生产单位
  let privateDescSeg2Map = new Map(); // 料品生命状态
  let shenzhenMap = new Map(); // 深圳
  let huizhouMap = new Map(); // 惠州

  // let specs = []

  const getTableData = async () => {
    if (!props.alternativeRuleDetail?.oid) return;
    pageLoading.value = true;
    toolbarOptions.value.keyword = '';
    tableSourceData.value = [];
    let param = {
      oid: props.alternativeRuleDetail?.oid,
      type: props.queryType,
      columns: tableColumns.value
    };
    const data = await proxy.apiFunTools.commandFunc('$pdmapis', 'part', 'queryPartList', param);
    console.log('data1', data)
    if (data?.length) {
      let list = bindingPropertiesItem(data);
      editVxeTable.value?.grid.loadData(list);
      tableSourceData.value = cloneDeep(list);
      handleSendCurReplacementTableData(list);
    }
    pageLoading.value = false;
  };
  const transferDataByAddList = async (list = []) => {
    if (!list?.length) return [];

    // modify by gejq 2025/2/18 规则列表要添加得数据增加权限（读取）校验
    let partIdList = list.map(item => item.oid);
    let param = {
      partIdList,
      type: props.queryType,
      columns: tableColumns.value
    };
    const data = await proxy.apiFunTools.commandFunc('$pdmapis', 'part', 'queryPartList', param);
    if (!data?.length) return [];
    // 创建oid到ibaAttrMapForSearch中规格值的映射
    // 清空 Map 中的所有键值对
    specMap.clear();
    manufactureUomMap.clear();
    privateDescSeg2Map.clear();
    huizhouMap.clear();
    shenzhenMap.clear();
    list.forEach(item => {
      if (item.ibaAttrMapForSearch && item.ibaAttrMapForSearch['702169844019150848']) {
        specMap.set(item.objectNumber, item.ibaAttrMapForSearch['702169844019150848']);
      }
      //生产单位
      if (item.ibaAttrMapForSearch?.['702170899427672064']) {
        manufactureUomMap.set(item.objectNumber, item.ibaAttrMapForSearch['702170899427672064']);
      }

      // 料品生命状态
      if (item.ibaAttrMapForSearch?.['702170103516545024']) {
        privateDescSeg2Map.set(item.objectNumber, item.ibaAttrMapForSearch['702170103516545024']);
      }
      //惠州
      if (item.ibaAttrMapForSearch?.['702171531085660160']) {
        huizhouMap.set(item.objectNumber, item.ibaAttrMapForSearch['702171531085660160']);
      }
      
      //深圳
      if (item.ibaAttrMapForSearch?.['702171505131307008']) {
        shenzhenMap.set(item.objectNumber, item.ibaAttrMapForSearch['702171505131307008']);
      }
      
    });

    // 更新data中的规格信息

    console.log('data', data);
    return data?.length ? data : [];
  };
  // const transferDataByAddList = async (list = []) => {
  //   if (!list?.length) return [];
  //   // modify by gejq 2025/2/18 规则列表要添加得数据增加权限（读取）校验
  //   let partIdList = list.map(item => item.oid);
  //   let param = {
  //     partIdList,
  //     type: props.queryType,
  //     columns: tableColumns.value
  //   };
  //   const data = await proxy.apiFunTools.commandFunc('$pdmapis', 'part', 'queryPartList', param);

  //   console.log('data2',data)

  //   return data?.length ? data : [];
  // };
  const initTableDataList = async () => {
    console.log('我进init')
    if (props.partDataDetail?.oid) {
      let data = await transferDataByAddList([props.partDataDetail]);
      console.log('initData')
      if (data?.length) {
        data.forEach(item => {
          item.amount = 1;
          item.rowId = proxy.$nanoid();
          item.masteredoid = item.masteredoid || item.oid;
          // modify by gejq 2025/3/11 赋值默认iba属性值

          if (Object.keys(defaultIbaValueMap.value)?.length) {

            item.ibaAttributeMap = {};
            for (let key in defaultIbaValueMap.value) {
              item.ibaAttributeMap[key] = [defaultIbaValueMap.value[key]];
              item = Object.assign(item, defaultIbaValueMap.value);
            }
          }
        });
        tableSourceData.value.push(...data);
        let tableData = cloneDeep(tableSourceData.value);
        editVxeTable.value?.grid.loadData(tableData);
        handleSendCurReplacementTableData(tableData);
      }
    }
  };
  const activeCellMethod = (column, columnIndex) => {
    console.log('执行成功', column);
    if (column.column.property === 'NetDemandRatio2') {
      if (column.row.mainMaterialIdentification === '1' && sessionStorage.getItem('way') === '3') {
        return true
      } else {
        return false
      }
    }

    return true
  };
  /**
   * @description 转换数据格式,并将iba数据绑在最外层数据源上
   * @Autor Gejq
   * @param {*} data 数据源
   */
  const bindingPropertiesItem = (data = []) => {
    if (data?.length) {
      let i = 0;
      while (data[i]) {
        data[i].rowId = proxy.$nanoid();
        data[i].masteredoid = data[i].masteredoid || data[i].oid;
        let j = 0;
        while (editColumns.value[j]) {
          if (editColumns.value[j]?.isIbaProperty) {
            data[i][editColumns.value[j].field] = data[i].ibaAttributeMap
              ? data[i].ibaAttributeMap[editColumns.value[j].field]
                ? data[i].ibaAttributeMap[editColumns.value[j].field].join('')
                : editColumns.value[j].value
              : editColumns.value[j].value;
          }
          j++;
        }
        i++;
      }
    }
    return data;
  };
  /**
   * @description 调用获取默认列配置的api接口
   * @Autor Gejq
   */
  const getDefaultColumnByViewNameToInvokeApi = async () => {
    if (!modulekeyParam.value?.modulekey) return;
    const res = await proxy.apiFunTools.commandFunc(
      '$pdmapis',
      'part',
      'getPdmFormByTypeIbaAndTableId',
      modulekeyParam.value.modulekey
    );
    return res || null;
  };
  /**
   * @function getDefaultColumnByViewName
   * @description 初始化列配置
   * @author gejq
   */
  const getDefaultColumnByViewName = async () => {
    const data = await getDefaultColumnByViewNameToInvokeApi();
    if (data) {
      let { rules, formData } = data;
      tableColumns.value = handleFormDataColumn(formData);
      gridOptions.value.editRules = rules || {};
      // 过滤出单位iba属性
      unitList.value = tableColumns.value.filter(item => item.unitType || item.unit);
    }
  };
  /**
   * @description 处理表单配置
   * @Autor Gejq
   * @param {*} formData 表单配置
   */
  const handleFormDataColumn = (formData = []) => {
    let columns = [];
    ibaColumnMap.value = {};
    if (formData?.length) {
      columns = formData.map(item => {
        // 将列中的iba约束缓存起来，在common-attribute-table.js中使用
        if (item.isIbaProperty) {
          let ibaColumnObj = {
            key: item.ibaOid,
            uniquelyMark: item.prop,
            constraintForm: [item]
          };
          if (item.options?.length) {
            ibaColumnObj.ibaEnumObj = item.options.reduce((total, next) => {
              total[next.value] = next.label;
              return total;
            }, {});
          }
          ibaColumnMap.value[item.prop] = [ibaColumnObj];
          // 收集默认iba值
          if (item.value) {
            defaultIbaValueMap.value[item.prop] = item.value;

          }
          defaultIbaValueMap.value['u9_item_sPECS'] = '';
          defaultIbaValueMap.value['u9_item_ManufactureUOM'] = '';
          defaultIbaValueMap.value['u9_item_PrivateDescSeg2'] = '';
          defaultIbaValueMap.value['u9_item_Warehouse'] = '';
          defaultIbaValueMap.value['u9_item_Warehouse02'] = '';

          console.log('握手default', defaultIbaValueMap.value)
        }
        let obj = {
          ...item,
          title: item.name,
          field: item.prop,
          elementType: item.type,
          $key: Math.random(),
          sortable: item.prop != 'typeIcon'
        };
        // modify by gejq 2025/2/17 type为radio时会显示异常以单选按钮显示,将type改为tyRadio
        obj.type = obj.type === 'radio' ? 'tyRadio' : obj.type;
        // 根据是否可编辑添加插槽
        if (!obj.readOnly) {
          obj.slots = {
            default: obj.prop,
            edit: `edit.${obj.prop}`
          };
          // 输入组件点击时自动获取焦点
          obj.editRender = { autofocus: '.el-input__inner' };
          // 处理枚举项
          if (obj?.typeParam?.[0] && obj.elementType === 'tySelect') {
            obj.editRender.enumKey = obj?.typeParam?.[0] || obj.field;
            obj.editRender.options = {
              clearable: false,
              filterable: true,
              list: obj.options
            };
            if (obj.isIbaProperty) {
              obj.editRender.options.clearable = true;
            }
          }
        } else {
          // 不可编辑列
          obj.slots = {
            default: obj.prop
          };
        }
        return obj;
      });
    }
    return columns;
  };
  const getIbaFormList = item => {
    return ibaColumnMap.value[item.prop] || [];
  };
  const updateMixinsJsIbaValues = (row, prop) => {
    let value = row[prop];
    let flag = selection.value.some(item => item.masteredoid == row.masteredoid);
    if (flag) {
      let i = 0;
      while (selection.value[i]) {
        if (selection.value[i].masteredoid) {
          selection.value[i][prop] = value;
          selection.value[i][`${prop}MsgTips`] = row[`${prop}MsgTips`] || '';
        }
        i++;
      }
    } else {
      let currentRow = editVxeTable.value?.grid.getRowById(row.rowId);
      if (currentRow) {
        currentRow[prop] = row[prop];
        currentRow[`${prop}MsgTips`] = row[`${prop}MsgTips`] || '';
      }
    }
  };
  /**
   * @description 复选框选择
   * @autor gejq
   * @param {*} records 复选框勾选值
   */
  const handleSelectionChange = ({ records }) => {
    selection.value = records;
  };
  /**
   * @description 复选框全选
   * @autor gejq
   * @param {*} records 复选框勾选值
   */
  const handleAllSelect = ({ records }) => {
    selection.value = records;
  };
  /**
   * @description 单元格classname
   * @autor gejq
   * @param {*} row 当前行
   * @param {*} column 列信息
   * @return {*} class
   */
  const cellClassName = ({ row, column }) => {
    let cellClass = '';
    if (row?.masteredoid && column.property && column.editRender) {
      let ibaList = ibaColumnMap.value[column.property] || [];
      let obj = ibaList?.length ? ibaList.find(item => item.uniquelyMark == column.property) : null;
      let constraintForm = obj?.constraintForm ? obj?.constraintForm[0] : '';
      if ((constraintForm?.required || column.property == 'amount') && !row[column.property]) {
        return 'requiredClass' + ' ' + cellClass;
      }
    }
    return cellClass;
  };
  const queryAddRef = ref(null);
  const queryAddObj = ref({
    dialogVisible: false,
    addKey: 'bomQueryAdd',
    defaultSelectionList: [],
    options: {
      defaultTypeList: ['ty.inteplm.part.CTyPart'],
      defaultTypeFroze: true,
      showTab: ['searchSettingTemplate'],

      parentComponent: '',
      searchLog: true,
      defaultView: 'Part',
      defaultViewChange: true,
      multiple: true,
      defaultContanier: {},
      defaultCondition: [{
        "propertyName": "variation1",
        "propertyValue": sessionStorage.getItem('var')
      }],
      isUseDefaultCondition: true
    },
    modulekeyParam: {
      modulekey: 'Query Add Part'
    }
  });
  /**
   * @description 查询添加
   * @Autor Gejq
   */
  const handleClickAddRow = () => {
    queryAddObj.value.dialogVisible = true;
    queryAddObj.value.options.defaultCondition = [{
      "propertyName": "variation1",
      "propertyValue": sessionStorage.getItem('var')
    }]
  };
  const handleAddAlreadyDataTips = (addList, masteroidList, tableName = '', relateTableName = '') => {
    let nameStr = '';
    addList.forEach(item => {
      if (item.masteredoid && masteroidList.indexOf(item.masteredoid) > -1) {
        nameStr = nameStr ? nameStr + '、' + `${item.objectNumber},${item.name}` : `${item.objectNumber},${item.name}`;
      }
    });
    if (nameStr) {
      proxy.$tyPlmNotification({
        type: 'info',
        title: proxy.$t('addTips'),
        dangerouslyUseHTMLString: true,
        message: proxy.$t('partAlreadyNotAddSamePart', { name: nameStr, tableName, relateTableName })
      });
      return true;
    }
    return false;
  };
  /**
   * @description 查询添加确认按钮
   * @Autor Gejq
   */
  const handleSubmitAddObj = async () => {
    let addList = queryAddRef.value?.getSelectedList();
    //判断当前物料是否为已发布
    let notReleaseList = addList.filter(item => item.lifecyclestagekey != 'RELEASED')
    // if (notReleaseList.length) {
    //   proxy.$tyPlmMessage.info('当前选中的物料中包含未发布的物料，不能添加')
    //   return
    // }
    console.log('当前物料', props.relatePartList);

    if (!addList?.length) return proxy.$tyPlmMessage.info(proxy.$t('label.plsSelectData'));
    // 1.判断要添加的数据是否在当前表格中已存在
    let flag = props.queryType == 'multiAlternateForPart';
    let masteroidList = getTableDataList().map(item => item.masteredoid);
    let relateTableName = flag ? proxy.$t('label.replacement') : proxy.$t('label.replacementPart');
    let blomA = handleAddAlreadyDataTips(addList, masteroidList, '', relateTableName);
    if (blomA) return;
    // 2.判断要填加的数据是否在相对列表中已存在(替代机 <--> 被替代件)
    if (props.relatePartList?.length) {
      let relateMasteroidList = props.relatePartList.map(item => item.masteredoid);
      let tableName = flag ? proxy.$t('label.replacementPart') : proxy.$t('label.replacement');
      let blomB = handleAddAlreadyDataTips(addList, relateMasteroidList, tableName, relateTableName);
      if (blomB) return;
    }
    console.log('addList', addList)
    // 3.从接口获取格式一致的数据
    let addData = await transferDataByAddList(addList);
    console.log('我是add', addData)
    if (addData?.length) {
      addData.forEach(item => {
        item.amount = 1;
        item.rowId = proxy.$nanoid();
        item.masteredoid = item.masteredoid || item.oid;
        item.disabled = false
        console.log(item);

        item.partDescription = item.extAttrMapForSearch?.description || '';
        if (props.alternativeRuleDetail?.oid) {
          item.action = 'Add';
          addSaveData.value.push(item.masteredoid);
        }
        // modify by gejq 2025/3/11 赋值默认iba属性值
        if (Object.keys(defaultIbaValueMap.value)?.length) {
          item.ibaAttributeMap = {};
          console.log('defaultIbaValueMap', defaultIbaValueMap.value)
          for (let key in defaultIbaValueMap.value) {

            item.ibaAttributeMap[key] = [defaultIbaValueMap.value[key]];
            item = Object.assign(item, defaultIbaValueMap.value);
          }
          console.log('我是Item', item)
          console.log('默认值', defaultIbaValueMap.value);
          //设置单位
          item.ibaAttributeMap['unit'] = [item.defaultunitkey]
          item = Object.assign(item, { "unit": item.defaultunitkey });
          // 1.规格
          const specValue = specMap.get(item.objectNumber) || '';
          item.ibaAttributeMap['u9_item_sPECS'] = [specValue];
          item = Object.assign(item, { "u9_item_sPECS": specValue });
          
          // 2. 生产单位
          const manufactureUomValue = manufactureUomMap.get(item.objectNumber) || '';
          console.log('manufactureUomValue',manufactureUomValue)
          item.ibaAttributeMap['u9_item_ManufactureUOM'] = [manufactureUomValue];
          item = Object.assign(item, { "u9_item_ManufactureUOM": manufactureUomValue });

          // 3. 料品生命状态
          const privateDescSeg2Value = privateDescSeg2Map.get(item.objectNumber) || '';
          item.ibaAttributeMap['u9_item_PrivateDescSeg2'] = [privateDescSeg2Value];
          item = Object.assign(item, { "u9_item_PrivateDescSeg2": privateDescSeg2Value });
          //4 深圳
          let shenzhenValue = shenzhenMap.get(item.objectNumber) || '';
          
          //  shenzhenValue = shenzhenValue=='客供仓'? '106':'101'
           console.log('shenzhenValue',shenzhenValue)
          item.ibaAttributeMap['u9_item_Warehouse'] = [shenzhenValue];
          item = Object.assign(item, { "u9_item_Warehouse": shenzhenValue });

          // 5 惠州
          let huizhouValue = huizhouMap.get(item.objectNumber) || '';
          // huizhouValue = huizhouValue=='客供仓'? '106':'101'
           console.log('huizhouValue',huizhouValue)
          item.ibaAttributeMap['u9_item_Warehouse02'] = [huizhouValue];
          item = Object.assign(item, { "u9_item_Warehouse02": huizhouValue });
          
          //设置生效日期为当天
          item.ibaAttributeMap['effectiveDate'] = [formatDate(new Date())]
          item = Object.assign(item, { "effectiveDate": formatDate(new Date()) });
          console.log('默认值1', item);

        }
      });
      // 4.更新已经修改的数据
      let updateMap = getUpdateRecords();
      tableSourceData.value.push(...addData);
      let tableData = cloneDeep(tableSourceData.value);
      editVxeTable.value?.grid.loadData(tableData);

      handleUpdateTableData(updateMap);
      queryAddObj.value.dialogVisible = false;
      let $table = editVxeTable.value?.grid;
      let { fullData } = $table.getTableData();
      console.log('当前表格的数据', fullData);

      emit('change', fullData);
      handleSendCurReplacementTableData(fullData);
    }
  };
  const handleEvent = (value) => {
    console.log('收到跨组件事件:', value)
    if (value != '3') {
      //清除现有的净需求比例
      // let $table = editVxeTable.value?.grid;
      // let { fullData } = $table.getTableData();
      //替代件
      let $table = editVxeTable.value?.grid;
      let { fullData } = $table.getTableData();
      console.log('当前表格的数据', fullData);
      //被替代件
      props.relatePartList.forEach(item => {
        item.NetDemandRatio2 = '0.0000'
      })
      fullData.forEach(item => {
        item.NetDemandRatio2 = '0.0000'
      })
      emit('change', props.relatePartList);
      handleSendCurReplacementTableData(props.relatePartList);
      emit('change', fullData);
      handleSendCurReplacementTableData(fullData);
    }
    // 执行需要的方法
  }


  const getUpdateRecords = () => {
    return editVxeTable.value?.grid.getUpdateRecords().reduce((total, item) => {
      if (item.masteredoid) {
        total[item.masteredoid] = item;
      }
      return total;
    }, {});
  };
  const formatDate = (date) => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份补零
    const day = String(date.getDate()).padStart(2, '0');        // 日期补零
    return `${year}-${month}-${day}`;
  }
  const handleUpdateTableData = (updateMap = {}, list = []) => {
    if (updateMap && Object.keys(updateMap)?.length) {
      let fullData = list?.length ? list : getTableDataList();
      let i = 0;
      while (fullData[i]) {
        if (fullData[i].masteredoid && updateMap[fullData[i].masteredoid]) {
          fullData[i] = Object.assign(fullData[i], updateMap[fullData[i].masteredoid]);
        }
        i++;
      }
    }
  };
  /**
   * @description 移除
   * @Autor Gejq
   */
  const handleResetDelete = () => {
    if (!selection.value.length) return;
    let arrName = [];
    selection.value.forEach(item => {
      arrName.push(item.objectNumber);
    });
    let str = '<div style="display:flex;flex-wrap:wrap;max-height: 60vh;overflow: auto;margin-bottom:8px">';
    for (let i = 0; i < arrName.length; i++) {
      str += `<span style="margin:0 4px 4px 0;padding: 3px 4px;
        font-size: 12px;line-height: 18px;
        border-radius: 4px;background-color: #E7EAEC" class="ty-minor-text-color">${arrName[i]}</span>`;
    }
    proxy
      .$tyPlmConfirm({
        type: 'warning',
        title: proxy.$t('btn.sureDeleteTitle'),
        message: `${str}<span style="padding: 3px 0px;">${proxy.$t('message.batchRepalceRemoveTip')}</span>`,
        confirmButtonText: proxy.$t('btn.confirm'),
        cancelButtonText: proxy.$t('btn.cancel'),
        dangerouslyUseHTMLString: true
      })
      .then(() => {
        let list = [];
        selection.value.forEach(item => {
          list.push(item.masteredoid);
          if (props.alternativeRuleDetail?.oid && (!item.action || item.action != 'Add')) {
            deleteSaveData.value.push({
              action: 'Delete',
              linkOid: item.linkOid
            });
          }
        });
        editVxeTable.value?.grid.remove(selection.value);
        selection.value = [];
        // 从全部数据源中移除要删除的数据
        if (allTableData.value.length) {
          allTableData.value = allTableData.value.filter(
            item => item.masteredoid && list.indexOf(item.masteredoid) === -1
          );
        }
        // 从全部数据源中移除要删除的数据
        if (tableSourceData.value.length) {
          tableSourceData.value = tableSourceData.value.filter(
            item => item.masteredoid && list.indexOf(item.masteredoid) === -1
          );
        }
        if (addSaveData.value.length) {
          addSaveData.value = addSaveData.value.filter(item => item && list.indexOf(item) === -1);
        }
        let $table = editVxeTable.value?.grid;
        let { fullData } = $table.getTableData();
        handleSendCurReplacementTableData(fullData);
      });
  };
  /**
   * @description 获取数据源
   * @Autor Gejq
   * @return {*} 返回数据源
   */
  const getTableDataList = () => {
    let $table = editVxeTable.value?.grid;
    if (!$table) return [];
    let { fullData } = $table.getTableData();
    console.log(fullData);

    return fullData || [];
  };
  /**
   * @description 保存
   * @Autor Gejq
   */
  const getNeedSaveBatchOperateData = () => {
    let isLoad = toolbarOptions.value.keyword ? true : false;
    // 保存时清除检索值
    toolbarOptions.value.keyword = '';
    isLoad && handleChangeValue();
    allTableData.value = [];
    pageLoading.value = true;
    const elementA = document.querySelectorAll(`.box-table-${props.queryType}--class table td`);
    let flag = elementA && Array.from(elementA).some(td => td.classList.contains('requiredClass'));
    if (flag) {
      pageLoading.value = false;
      proxy.$tyPlmMessage.info(proxy.$t('cellRequiredInfo'));
      return null;
    }
    let param = getUpdateRecordsTableData();
    if (param == 'No') {
      pageLoading.value = false;
      proxy.$tyPlmMessage.info(proxy.$t('valideIbaAttribute'));
      return null;
    }
    param = [...param, ...deleteSaveData.value];
    if (!param.length) {
      pageLoading.value = false;
    }
    pageLoading.value = false;
    return param;
  };
  /**
   * @description 获取修改数据
   * @Autor Gejq
   * @return {*} 返回修改的数据
   */
  const getUpdateRecordsTableData = (prop = 'masteredoid') => {
    let flag = 'Yes';
    let updateRecords = [];
    let alreadyList = [];
    let fullData = getTableDataList();
    let sourceMap = tableSourceData.value.reduce((item, next) => {
      if (next[prop]) item[next[prop]] = next;
      return item;
    }, {});
    let i = 0;
    while (fullData[i]) {
      if (flag == 'No') break;
      if (fullData[i][prop]) {
        if (addSaveData.value.indexOf(fullData[i][prop]) === -1) {
          let ibaAttributeMap = fullData[i].ibaAttributeMap || {};
          let j = 0;
          while (editColumns.value[j]) {
            let nextValue = fullData[i][editColumns.value[j]?.field];
            let preValue = sourceMap[fullData[i][prop]][editColumns.value[j]?.field];
            if (fullData[i][prop] == sourceMap[fullData[i][prop]][prop] && nextValue !== preValue) {
              if (editColumns.value[j].isIbaProperty) {
                ibaAttributeMap[editColumns.value[j].prop] = [fullData[i][editColumns.value[j].field] || ''];
              }
            }
            // 存在校验未通过,返回校验值
            if (editColumns.value[j]?.field && fullData[i][`${editColumns.value[j]?.field}MsgTips`]) {
              flag = 'No';
              break;
            }
            j++;
          }
          // 1.将修改的数据加到list中
          let updateObj = {
            oid: fullData[i].masteredoid,
            otype: fullData[i].masteredotype,
            amount: fullData[i].amount,
            number: fullData[i].objectNumber,
            name: fullData[i].name,
            linkOid: fullData[i].linkOid || '',
            ibaAttributeMap
          };
          if (props.alternativeRuleDetail?.oid) updateObj.action = 'Update';
          updateRecords.push(updateObj);
          alreadyList.push(fullData[i].masteredoid);
        }
        // 2.将修改的数据加到list中
        if (addSaveData.value.indexOf(fullData[i][prop]) > -1) {
          let obj = getInsertPartList(fullData[i]);
          obj.action = 'Add';
          updateRecords.push(obj);
          alreadyList.push(fullData[i].masteredoid);
        }
        // 3.没有任何改动不加action放到list中
        if (alreadyList.indexOf(fullData[i][prop]) === -1) {
          let obj = getInsertPartList(fullData[i]);
          updateRecords.push(obj);
        }
      }
      i++;
    }
    return flag == 'Yes' ? updateRecords : flag;
  };
  /**
   * @description 缓存界面所有值
   * @Autor Gejq
   */
  const handleFocusValue = () => {
    let value = toolbarOptions.value.keyword;
    if (value) return;
    allTableData.value = cloneDeep(getTableDataList());
  };
  const handleClearKeyword = () => {
    toolbarOptions.value.keyword = '';
    handleChangeValue();
  };
  /**
   * @description 失焦时,清空界面缓存的所有值
   * @Autor Gejq
   */
  const handleBlurValue = () => {
    let value = toolbarOptions.value.keyword;
    if (value) return;
    allTableData.value = [];
  };
  /**
   * @description 当检索值改变时,重新渲染表格
   * @Autor Gejq
   */
  const handleChangeValue = () => {
    let searchValue = toolbarOptions.value.keyword;
    let list = cloneDeep(tableSourceData.value);
    let allUpdateMap = null;
    if (allTableData.value?.length) {
      allUpdateMap = allTableData.value.reduce((total, item) => {
        if (item.masteredoid) {
          total[item.masteredoid] = item;
        }
        return total;
      }, {});
    }
    if (!searchValue) {
      // modify by gejq 2024/11/12 更新复选框选中数据
      let map = selection.value.map(item => item.masteredoid);
      selection.value = [];
      let seletList = [];
      let updateMap = getUpdateRecords();
      editVxeTable.value?.grid.loadData(list);
      if (
        (updateMap && Object.keys(updateMap)?.length) ||
        (allUpdateMap && Object.keys(allUpdateMap)?.length) ||
        (map && Object.keys(map)?.length)
      ) {
        let i = 0;
        while (list[i]) {
          if (list[i]?.masteredoid) {
            if (allUpdateMap && Object.keys(allUpdateMap)?.length && allUpdateMap[list[i]?.masteredoid]) {
              list[i] = Object.assign(list[i], allUpdateMap[list[i]?.masteredoid]);
            }
            if (updateMap && Object.keys(updateMap)?.length && updateMap[list[i]?.masteredoid]) {
              list[i] = Object.assign(list[i], updateMap[list[i].masteredoid]);
            }
            if (map && Object.keys(map)?.length && map.indexOf(list[i]?.masteredoid) > -1) {
              seletList.push(list[i]);
            }
          }
          i++;
        }
      }
      selection.value = seletList;
      return;
    }
    let searchLower = searchValue.toLowerCase();
    let rowIdList = [];
    // modify by gejq 2024/11/12 更新复选框选中数据
    let map = selection.value.map(item => item.masteredoid);
    selection.value = [];
    let seletList = [];
    let i = 0;
    while (list[i]) {
      if (list[i]?.masteredoid) {
        let j = 0;
        while (tableColumns.value[j]) {
          if (tableColumns.value[j].field) {
            let value = getLabelByColumn.value(list[i], tableColumns.value[j].field, tableColumns.value[j]);
            let valueLower = value ? String(value).toLowerCase() : String(value);
            if (valueLower && valueLower.indexOf(searchLower) > -1 && rowIdList.indexOf(list[i].masteredoid) === -1) {
              rowIdList.push(list[i].masteredoid);
              break;
            }
          }
          j++;
        }
        if (list[i]?.masteredoid && map.indexOf(list[i]?.masteredoid) > -1) {
          seletList.push(list[i]);
        }
      }
      i++;
    }
    let orginTable = tableSourceData.value.filter(item => rowIdList.indexOf(item.masteredoid) > -1);
    let newOrginTable = cloneDeep(orginTable);
    editVxeTable.value?.grid.loadData(newOrginTable);
    selection.value = seletList;
    handleUpdateTableData(allUpdateMap, newOrginTable);
  };
  const getInsertPartList = row => {
    let ibaAttributeMap = getEditAttributeByTable(row);
    let obj = {
      oid: row.masteredoid,
      otype: row.masteredotype,
      amount: row.amount,
      number: row.objectNumber,
      name: row.name,
      linkOid: row.linkOid || '',
      ibaAttributeMap
    };
    return obj;
  };
  const getEditAttributeByTable = (row = {}) => {
    let ibaAttributeMap = row.ibaAttributeMap || {};
    if (editColumns.value?.length) {
      let i = 0;
      while (editColumns.value[i]) {
        if (editColumns.value[i].isIbaProperty) {
          ibaAttributeMap[editColumns.value[i].prop] = [row[editColumns.value[i].field] || ''];
        }
        i++;
      }
    }
    return ibaAttributeMap;
  };
  const resetFieldData = () => {
    if (!editVxeTable.value?.grid) return;
    editVxeTable.value?.grid.clearAll();
    editVxeTable.value?.grid.loadData([]);
    tableSourceData.value = [];
  };
  const handleInputChange = (row, prop, value) => {
    if (prop === 'amount') {
      let regx = /^(?!0\d)(\d+|\d*\.\d+)$/;
      value = String(value)?.replace(/[^0-9.]/g, '');
      row[`${prop}MsgTips`] = value && !regx.test(value) ? this.$t('message.numErrorMsgTips') : '';
    }
    let flag = selection.value.some(item => item.masteredoid == row.masteredoid);
    if (flag) {
      let i = 0;
      while (selection.value[i]) {
        if (selection.value[i].masteredoid) {
          selection.value[i][prop] = value ? Number(value) : '';
          selection.value[i][`${prop}MsgTips`] = row[`${prop}MsgTips`] || '';
        }
        i++;
      }
    } else {
      row[prop] = value ? Number(value) : '';
    }
  };
  const handleSendCurReplacementTableData = (data = []) => {
    // 发送给祖先组件(creat-update-rule.js),用于表格重复添加校验
    proxy.eventBus.bus.emit('sendCurReplacementTableData', { data, type: props.queryType });
  };
  const handleEditActivated = () => {
    // 设置其他单元格组件自动聚焦
    setTimeout(() => {
      let $elDom = editVxeTable.value.$el;
      let selectItem = $elDom.querySelector('.el-select__selection');
      // 手动聚焦el-select
      if (selectItem) {
        // 创建并派发鼠标点击事件
        const clickEvent = new MouseEvent('click', { bubbles: true, cancelable: true });
        selectItem.dispatchEvent(clickEvent);
      }
    }, 20);
  };
  // modify by gejq 2025/3/11 点击空白地方取消列表编辑态
  const onClickOutside = () => {
    setTimeout(() => {
      let $editVxeTable = editVxeTable.value?.grid;
      if (!$editVxeTable) return;
      $editVxeTable.clearEdit && $editVxeTable.clearEdit();
    }, 20);
  };
  return {
    toolbarOptions,
    checkboxConfig,
    originGridOptionsColumns,
    tableColumns,
    showMark,
    modulekeyParam,
    pageLoading,
    unitList,
    substitutionTableConfig,
    isSaveData,
    selection,
    updateRecordsParam,
    allTableData,
    editVxeTable,
    gridOptions,
    btnOptions,
    defaultColumns,
    editColumns,
    editItem,
    selectionOrRowList,
    getLabelByColumn,
    getIbaFormList,
    updateMixinsJsIbaValues,
    initData,
    getTableData,
    bindingPropertiesItem,
    getDefaultColumnByViewNameToInvokeApi,
    getDefaultColumnByViewName,
    handleFormDataColumn,
    handleSelectionChange,
    handleAllSelect,
    cellClassName,
    handleClickAddRow,
    handleResetDelete,
    getTableDataList,
    getNeedSaveBatchOperateData,
    getUpdateRecordsTableData,
    handleFocusValue,
    handleClearKeyword,
    handleBlurValue,
    handleChangeValue,
    queryAddObj,
    handleSubmitAddObj,
    queryAddRef,
    getInsertPartList,
    resetFieldData,
    handleInputChange,
    handleEditActivated,
    onClickOutside
  };
};
